package util.concurrent;

import org.junit.Assert;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;


/**
 * //中断线程（实例方法）
 * public void thread.interrupt();
 * <p>
 * //判断线程是否被中断（实例方法）
 * public boolean thread.isInterrupted();
 * <p>
 * //判断是否被中断并清除当前中断状态（静态方法）
 * public static boolean Thread.interrupted();
 * <p>
 * 链接：https://juejin.im/post/5b57eb35f265da0f7c4fcd25
 */
public class Thread_ {

    public static void main(String[] args) {
//      test1();
        test2();
    }

    private static void test1() {
        Thread thread = new Thread(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                System.out.println("handle exception,assert ok?");

                Thread t = Thread.currentThread();

                //catch 到异常后恢复中断状态
                Assert.assertFalse(t.isInterrupted());

                //将状态设置为中断
                t.interrupt();
                Assert.assertTrue(t.isInterrupted());

                //返回中断状态,并且重置
                Assert.assertTrue(Thread.interrupted());

                //中断状态已被设置为false
                Assert.assertFalse(t.isInterrupted());
            }
        });


        thread.start();
        thread.interrupt();//中断
    }

    private static void test2() {

        Thread thread = new Thread(() -> {
            System.out.println("开始");

            //标记中断, park 立刻返回
            //Thread.currentThread().interrupt();

            Assert.assertFalse(Thread.currentThread().isInterrupted());
            LockSupport.park();

            System.out.println("结束");
        });

        thread.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LockSupport.unpark(thread);
    }
}
